import os
import logging
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.ext.webapp.util import login_required
from models import *
from django.utils import simplejson
from datetime import datetime, timedelta
import time
from google.appengine.api.urlfetch import fetch

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.response.out.write(template.render('templates/index.html', {
            'projects': db.GqlQuery("SELECT * FROM Project"),
            'connected': Browser.all().filter('last_checkin >', datetime.now() - timedelta(seconds=65))
        }))
    
    def post(self):
        data = simplejson.loads(self.request.body)
        project = db.GqlQuery("SELECT * FROM Project WHERE name = :1", 
            data['project_name']).get()
        if project:
            if project.hudson_ping_url:
                url = "%s%s" % (project.hudson_ping_url, 
                    data['revisions'][0]['revision'])
                fetch(url, payload=self.request.body, method='POST')
            project.repository_path = data['repository_path']
            project.put()
            for d in data['revisions']:
                exists = db.GqlQuery("SELECT * FROM Revision WHERE name = :1", 
                    d['revision']).get()
                if not exists:
                    logging.debug(d)
                    rev = Revision(
                        name=str(d['revision']),
                        project=project,
                        url=d['url'],
                        author=d['author'],
                        timestamp=datetime.fromtimestamp(d['timestamp']),
                        message=d['message'],
                        added=d['added'],
                        modified=d['modified'],
                        removed=d['removed'],
                    )
                    rev.put()
                    for browser in Browser.all():
                        browser.add_to_queue(rev)
                    rev.compile()
                    
        self.response.out.write('thanks!')


class ResultHandler(webapp.RequestHandler):
    
    def get(self, name):
        project = db.GqlQuery("SELECT * FROM Project WHERE name = :1", 
            name).get();
        revs = db.GqlQuery("SELECT * FROM Revision WHERE project = :1 ORDER BY timestamp DESC", project).fetch(50)
        self.response.out.write(template.render('templates/results.html', {
            'project': project,
            'latest': revs[0],
            'revisions': revs
        }))

class RevisionHandler(webapp.RequestHandler):

    def get(self, revision):
        rev = db.GqlQuery("SELECT * FROM Revision WHERE name = :1", 
            revision).get();
        self.response.out.write(template.render('templates/result.html', {
            'project': rev.project,
            'rev': rev,
        }))

class RunnerHandler(webapp.RequestHandler):

    def get(self):
        self.response.out.write(template.render('templates/runner.html', {
            'projects': db.GqlQuery("SELECT * FROM Project")
        }))

class TestsHandler(webapp.RequestHandler):

    def get(self):
        browser = Browser.all().filter('name =', 
            self.request.get('browser')).get()
        if not browser:
            browser = Browser(name=self.request.get('browser'))
            browser.put()
            for project in Project.all():
                for rev in Revision.all().order('-timestamp').fetch(50):
                    browser.add_to_queue(rev)
        rev = browser.next_revision()
        browser.last_checkin = datetime.now()
        browser.put()
        if rev:
            self.response.out.write("%s&log=true&cachebust=%s" % (rev.test_url(), 
                time.mktime(time.localtime())))

    def post(self):
        data = simplejson.loads(self.request.get('data'))
        logging.debug(data)
        rev = Revision.all().filter('name = ', data['revision']).get()
        rev.add_testrun(data['total'], data['browserName'], data['failures'], data['supported'], data['error'])
        self.response.out.write(template.render('templates/done.html', {}))
                
        
class CompileHandler(webapp.RequestHandler):

    def get(self):
        rev = db.GqlQuery(
            "SELECT * FROM Revision WHERE compiled = FALSE").get();
        if rev:
            rev.compile()
            self.response.out.write("compiled")
        else:
            self.response.out.write("no revisions needing compiling found")

def main():
    application = webapp.WSGIApplication([
            ('/', MainHandler), 
            ('/results/(.*)', ResultHandler),
            ('/revisions/(.*)', RevisionHandler),
            ('/runner', RunnerHandler),
            ('/tests', TestsHandler),
            ('/tasks/compile', CompileHandler),
        ],
        debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
